package cn.elwy.rcp.ui.table.adapter;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.elwy.rcp.ui.table.TablePane;
import cn.elwy.rcp.ui.table.model.ColumnInfo;
import cn.elwy.rcp.ui.table.util.ReflectUtil;

public class CellModifierAdapter implements ICellModifier {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	protected Map<String, Object> valueCache = new HashMap<String, Object>();
	protected Viewer viewer;
	protected boolean isTable;
	protected Map<String, ColumnInfo> columnInfoMap;
	protected TableEditorAdapter tableEditorAdapter;

	public CellModifierAdapter(TableEditorAdapter tableEditorAdapter) {
		this.tableEditorAdapter = tableEditorAdapter;
		TablePane tablePane = tableEditorAdapter.getTablePane();
		this.viewer = tablePane.getTableViewer();
		this.columnInfoMap = tableEditorAdapter.getColumnInfoMap();
		this.isTable = tablePane.getTableInfo().isTable();
	}

	public boolean canModify(Object element, String property) {
		ColumnInfo columnInfo = columnInfoMap.get(property);
		return columnInfo.isCanEditor();
	}

	public Object getValue(Object element, String property) {
		Object value = null;
		if (isTable) {
			value = ReflectUtil.getTableColumnValue(element, property, true);
		} else {
			value = ReflectUtil.getTreeColumnValue(element, property, true);
		}
		if (value == null) {
			value = "";
		}
		String result = value.toString();
		valueCache.put(property, result);
		return result;
	}

	public void modify(Object element, String property, Object value) {
		if (value.equals(valueCache.get(property))) {
			return;
		}
		if (element instanceof Item) {
			element = ((Item) element).getData();
		}
		if (isTable) {
			ReflectUtil.setTableColumnValue(element, property, value, true);
		} else {
			ReflectUtil.setTreeColumnValue(element, property, value, true);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("old:" + valueCache.get(property) + "new:" + value);
		}
		viewer.refresh();
	}
}